package com.example.administrator.yanfoxconn.activity;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.example.administrator.yanfoxconn.R;
import com.example.administrator.yanfoxconn.adapter.CanYinAdapter;
import com.example.administrator.yanfoxconn.bean.CanYinInfo;
import com.example.administrator.yanfoxconn.bean.EmpFile;
import com.example.administrator.yanfoxconn.bean.EmpMessage;
import com.example.administrator.yanfoxconn.bean.KHInfo;
import com.example.administrator.yanfoxconn.bean.SelectModel;
import com.example.administrator.yanfoxconn.constant.Constants;
import com.example.administrator.yanfoxconn.constant.FoxContext;
import com.example.administrator.yanfoxconn.constant.ImageCaptureManager;
import com.example.administrator.yanfoxconn.intent.PhotoPickerIntent;
import com.example.administrator.yanfoxconn.utils.BaseActivity;
import com.example.administrator.yanfoxconn.utils.FileUtil;
import com.example.administrator.yanfoxconn.utils.HttpConnectionUtil;
import com.example.administrator.yanfoxconn.utils.HttpUtils;
import com.example.administrator.yanfoxconn.utils.ImageZipUtils;
import com.example.administrator.yanfoxconn.utils.StringUtils;
import com.example.administrator.yanfoxconn.utils.TimeDateUtils;
import com.example.administrator.yanfoxconn.utils.ToastUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONArray;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 用途：人資-訪談記錄 添加單頭界面
 * Created by Song on 2021/9/14.
 */
public class KHAddMainActivity extends BaseActivity implements View.OnClickListener{

    private final int MESSAGE_SET_PLAN = 111;//类型
    private final int MESSAGE_SET_AREA = 222;//区域
    private final int MESSAGE_SET_BUILD = 333;//楼栋

    @BindView(R.id.tv_title)
    TextView tvTitle;//標題
    @BindView(R.id.btn_title_left)
    Button btnBack;//返回
    @BindView(R.id.btn_title_right)
    Button btnAdd;//下一步

    @BindView(R.id.sp_type)
    Spinner spType;//访谈类型
    @BindView(R.id.sp_area)
    Spinner spArea;//访谈地址 区
    @BindView(R.id.sp_build)
    Spinner spBuilding;//访谈地址 栋
    @BindView(R.id.et_position)
    EditText etPosition;//具体位置
    @BindView(R.id.ll_actual)
    LinearLayout container;//父控件
    @BindView(R.id.et_id)
    EditText etIdF;//標題
    @BindView(R.id.btncheck)
    Button btnC;//
    @BindView(R.id.tv_name)
    TextView tvNameF;//標題
    @BindView(R.id.tv_dep)
    TextView tvDepF;//標題
    private List<EmpMessage> empMessagesList,nempMessagesList;

    @BindView(R.id.iv_empty1)
    ImageView ivEmptyOne;//空白图片占位
    @BindView(R.id.gv_photo1)
    GridView gridViewOne;//图片显示区域
    private static final int REQUEST_CAMERA_CODE_ONE = 111;
    private static final int REQUEST_PREVIEW_CODE_ONE = 221;
    private ArrayList<String> imagePathsOne = null;//圖片未壓縮地址
    private ArrayList<String> imgZipPathsOne = new ArrayList<String>();//圖片壓縮后地址
    private ArrayList<String> imagePathsTwo = null;//圖片未壓縮地址
    private ImageCaptureManager captureManager; // 相机拍照处理类
    private GridAdapter gridAdapterOne;

    private List<KHInfo> typeInfo,areaInfo,buildInfo;//访谈类型，区域，楼栋
    private String type,area,build;
    private KHAddMainActivity mContext = this;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kh_add_main);
        ButterKnife.bind(this);
        btnBack.setOnClickListener(this);
        tvTitle.setText("新增访谈");
        btnAdd.setText("提交");
        btnAdd.setVisibility(View.VISIBLE);
        btnAdd.setOnClickListener(this);
        btnBack.setOnClickListener(this);
        ivEmptyOne.setOnClickListener(this);

        Button btnAdd = findViewById(R.id.btn);
        btnAdd.setOnClickListener(this);
        if (num==0){
            etIdF.setText(FoxContext.getInstance().getLoginId());
            btnC.setVisibility(View.GONE);
        }
        getType("i_type");
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_title_left://返回
                finish();
                break;
            case R.id.btn_title_right://提交
                check();
                break;
            case R.id.iv_empty1:
            PhotoPickerIntent intent = new PhotoPickerIntent(mContext);
            intent.setSelectModel(SelectModel.MULTI);
            intent.setShowCarema(true); // 是否显示拍照
            intent.setMaxTotal(9); // 最多选择照片数量，默认为3
            intent.setSelectedPaths(imagePathsOne); // 已选中的照片地址， 用于回显选中状态

            startActivityForResult(intent, REQUEST_CAMERA_CODE_ONE);
            break;

            case R.id.btn:
                // 根据tag区分是新增view还是删除view
                String tag = (String) view.getTag();
                if ("-".equals(tag)) {
                    // 删除view
                    num--;
                    // 获取子控件
                    View child = (View) view.getParent();
                    // 从父控件中移除子控件
                    container.removeView(child);
                } else {
                    num++;
                    // 新增view
                    // 创建子控件实例
                    View child = LayoutInflater.from(mContext).inflate(R.layout.add_people, container, false);
                    // 获取其中的button
                    View btn = child.findViewById(R.id.btn);
                    // 监听点击事件
                    btn.setOnClickListener(this);
                    // 设置删除的tag
                    btn.setTag("-");
                    btn.setBackgroundDrawable(ContextCompat.getDrawable(this.getApplication(), R.mipmap.icon_minus));

                    final EditText etId = child.findViewById(R.id.et_id);
                    final TextView tvName=child.findViewById(R.id.tv_name);
                    final TextView tvDep=child.findViewById(R.id.tv_dep);
                    final Button btnc=child.findViewById(R.id.btncheck);
                    btnc.setOnClickListener(this);
                    btnc.setVisibility(View.VISIBLE);

                    btnc.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            getMessage(etId.getText().toString(),tvName,tvDep);

                            btnc.setVisibility(View.GONE);
                        }
                    });

                    etId.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(CharSequence s, int start, int before, int count) {

                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            btnc.setVisibility(View.VISIBLE);
                            tvName.setText("");
                            tvDep.setText("");
                        }
                    });


                    // 添加进父控件
                    container.addView(child);
                }
                // 请求重绘
                container.invalidate();

                break;
        }
    }
    //基本信息下拉   傳值：flag type
    private void getType(String flag){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_BASIC_INFO + "?flag=" + flag;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        typeInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            typeInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_PLAN;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setType(){
        List<String> typeName=new ArrayList<>();
        for (int i = 0;i<typeInfo.size();i++){
            typeName.add(typeInfo.get(i).getNAME());
        }
        //下拉列表選擇
        spType.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, typeName));
        spType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                type=typeName.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉：区域
    private void getArea(){
        new Thread() {
            @Override
            public void run() {
                String url2 = Constants.HTTP_AREA_LIST;

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        areaInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            areaInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_AREA;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setArea(){
        List<String> areaName=new ArrayList<>();
        for (int i = 0;i<areaInfo.size();i++){
            areaName.add(areaInfo.get(i).getBs_area());
        }
        //下拉列表選擇
        spArea.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, areaName));
        spArea.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                area=areaName.get(position);
                getBuild(area);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //基本信息下拉:栋别   傳值：area
    private void getBuild(String area){
        new Thread() {
            @Override
            public void run() {

                String url2 = null;
                try {
                    url2 = Constants.HTTP_BUILD_LIST + "?area=" + StringUtils.getToHttp(area);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                Log.e("---------", "url2==fff===" + url2);
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url2);
                dismissDialog();
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);
                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        buildInfo = new ArrayList<KHInfo>();

                        for (JsonElement type : array) {
                            KHInfo humi = gson.fromJson(type, KHInfo.class);
                            buildInfo.add(humi);
                        }
                        Message message = new Message();
                        message.what = MESSAGE_SET_BUILD;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                } else {
                    Message message = new Message();
                    message.what = Constants.MESSAGE_NETMISTAKE;
                    mHandler.sendMessage(message);
                    finish();
                }
            }
        }.start();
    }
    private void setBuild(){
        List<String> buildName=new ArrayList<>();
        for (int i = 0;i<buildInfo.size();i++){
            buildName.add(buildInfo.get(i).getBs_build());
        }
        //下拉列表選擇
        spBuilding.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, buildName));
        spBuilding.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                build=buildName.get(position);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    //獲取人员信息F
    private void getMessageF(String id){
        showDialog();
        final String url = Constants.HTTP_COMMON_FORMS_SERVLET+"?code="+id;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);

                dismissDialog();
                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        empMessagesList = new ArrayList<EmpMessage>();

                        for (JsonElement type : array) {
                            EmpMessage humi = gson.fromJson(type, EmpMessage.class);
                            empMessagesList.add(humi);
                        }

                        Message message = new Message();
                        message.what = Constants.MESSAGE_SET_TEXT;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                }
            } }.start();
    }

    private TextView nname,ndep;
    //獲取人员信息
    private void getMessage(String id,TextView name,TextView dep){
        showDialog();
        nname=name;
        ndep=dep;
        final String url = Constants.HTTP_COMMON_FORMS_SERVLET+"?code="+id;

        new Thread() {
            @Override
            public void run() {
                //把网络访问的代码放在这里
                String result = HttpUtils.queryStringForPost(url);

                dismissDialog();
                Log.e("---------", "==fff===" + url);
                Gson gson = new Gson();
                if (result != null) {
                    Log.e("---------", "result==fff===" + result);

                    JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                    String errCode = jsonObject.get("errCode").getAsString();
                    if (errCode.equals("200")) {
                        JsonArray array = jsonObject.get("data").getAsJsonArray();
                        nempMessagesList = new ArrayList<EmpMessage>();

                        for (JsonElement type : array) {
                            EmpMessage humi = gson.fromJson(type, EmpMessage.class);
                            nempMessagesList.add(humi);
                        }

                        Message message = new Message();
//                        message.what = Constants.MESSAGE_SET_TEXT;
                        message.what = 1111;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);

                    } else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_TOAST;
                        message.obj = jsonObject.get("errMessage").getAsString();
                        mHandler.sendMessage(message);
                    }
                }
            } }.start();
    }
    String followName = "";

    //提交前檢查
    private void check(){
        if(FoxContext.getInstance().getLoginId().equals("")){
            ToastUtils.showLong(mContext,"登錄超時,請退出重新登錄!");
            return;
        }
        if (etPosition.getText().toString().equals("")){
            ToastUtils.showShort(mContext,"請輸入具体位置！");
            return;
        }

        List<String> ids = new ArrayList<>();

        for (int i = 0; i < container.getChildCount(); i++) {
//            String names;
            View childAt = container.getChildAt(i);
            EditText hotelId = (EditText) childAt.findViewById(R.id.et_id);
            TextView hotelName = (TextView) childAt.findViewById(R.id.tv_name);
            if (!hotelId.getText().toString().equals("")) {
                ids.add(hotelId.getText().toString());
            } else {
                ToastUtils.showShort(this, "不能有空數據,請確認!!!!");
                ids.clear();
                break;
            }
            if (!hotelName.getText().toString().equals("")) {

                if (i==0){
                    followName="";
                }else if (i==1){
                    followName=hotelName.getText().toString();
                }else{
                    followName=followName+","+hotelName.getText().toString();
                }
            } else {
                ToastUtils.showShort(this, "不能有空數據,請確認!!!!");
                followName = "";
                break;
            }
        }

        if (imagePathsOne==null) {
            ToastUtils.showShort(this, "請上傳服務照片");
            return;
        }
        upMsessage();
    }
    //提交信息
    private void upMsessage() {

        final String url = Constants.HTTP_HEAD_ADD; //此處寫上自己的URL

        JsonObject object = new JsonObject();

        JsonArray photoArray1 = new JsonArray();

        if (imagePathsOne != null) {
            for (int i = 0; i < imagePathsOne.size(); i++) {
                File pictureFile = new File(imagePathsOne.get(i)); //通過路徑獲取檔
                final String pic_path = imagePathsOne.get(i);
                String sign_dir = Environment.getExternalStorageDirectory() + File.separator + "YanFoxconn" + File.separator + "Photos";
                String _path =  sign_dir + File.separator  + System.currentTimeMillis() +i+ ".jpg";
                final String compressImage = ImageZipUtils.compressImage(pic_path, _path, 30);
                String picBase64Code = ImageZipUtils.imageToBase64(compressImage);
                JsonObject jsonObject1 = new JsonObject();
                jsonObject1.addProperty("file", picBase64Code);
                photoArray1.add(jsonObject1);
            }
            object.add("photo", photoArray1);
        }

        object.addProperty("i_type",type);
        object.addProperty("i_empNo",FoxContext.getInstance().getLoginId());
        object.addProperty("i_empname",FoxContext.getInstance().getName());
        object.addProperty("i_empdep",tvDepF.getText().toString());
        object.addProperty("i_area",area);
        object.addProperty("i_building",build);
        object.addProperty("i_position",etPosition.getText().toString());
        object.addProperty("i_follow", followName);
        object.addProperty("i_lng",FoxContext.getInstance().getLocation().getLongitude());
        object.addProperty("i_lat",FoxContext.getInstance().getLocation().getLatitude());

        Log.e("----object----",  object.toString());

        //開啟一個新執行緒，向伺服器上傳資料
        new Thread() {
            public void run() {
                //把网络访问的代码放在这里
                try {
                    showDialog();
                    Log.e("-----url----",  url);
                    String result = HttpConnectionUtil.doPostJsonObject(url, object);
                    if (result != null) {
                        dismissDialog();
                        Log.e("----result-----",  result);
                        JsonObject jsonObject = new JsonParser().parse(result).getAsJsonObject();
                        String errCode = jsonObject.get("errCode").getAsString();
                        if (errCode.equals("200")) {
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);

                        } else{
                            Message message = new Message();
                            message.what = Constants.MESSAGE_ALERT;
                            message.obj = jsonObject.get("errMessage").getAsString();
                            mHandler.sendMessage(message);
                        }
                    }else{
                        Message message = new Message();
                        message.what = Constants.MESSAGE_NETMISTAKE;
                        mHandler.sendMessage(message);
                        finish();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    FileUtil.deletePhotos(mContext);
                }
            }
        }.start();
    }

    private int num=0;
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case Constants.MESSAGE_TOAST://Toast彈出
                    ToastUtils.showLong(mContext, msg.obj.toString());
//                    finish();
                    break;
                case 1111://text賦值
//                    aboutAlert(msg.obj.toString(),MESSAGE_SET_TEXT);

                        Log.e("---------",num+"==num");
                        nname.setText(nempMessagesList.get(0).getCHINESENAME());
                        ndep.setText(nempMessagesList.get(0).getORGNAME());

                        nempMessagesList.clear();
                        break;
                case Constants.MESSAGE_SET_TEXT://text賦值
                    if (num==0){
                        Log.e("---------",num+"==num");
                        tvNameF.setText(empMessagesList.get(0).getCHINESENAME());
                        tvDepF.setText(FoxContext.getInstance().getRelDep());
                        empMessagesList.clear();
                    }
                    break;
                case Constants.MESSAGE_UP://提交響應
//                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
//                    ToastUtils.showLong(CrossScanActivity.this, msg.obj.toString());
                    break;
                case Constants.MESSAGE_ALERT://提交響應
//                    worningAlert(msg.obj.toString(),Constants.MESSAGE_TOAST);
                    ToastUtils.showLong(KHAddMainActivity.this, msg.obj.toString());
                   finish();
                    break;
                case MESSAGE_SET_PLAN:
                    setType();
                    getArea();
                    break;
                case MESSAGE_SET_AREA:
                    setArea();
                    break;
                case MESSAGE_SET_BUILD:
                    setBuild();
                    getMessageF(FoxContext.getInstance().getLoginId());

                    break;
            }
            super.handleMessage(msg);
        }
    };
    //照片上傳 返回
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {

            switch (requestCode) {
                // 选择照片
                case REQUEST_CAMERA_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPickerActivity.EXTRA_RESULT), requestCode);
                    break;
                // 预览
                case REQUEST_PREVIEW_CODE_ONE:
                    loadAdpater(data.getStringArrayListExtra(PhotoPreviewActivity.EXTRA_RESULT), requestCode);
                    break;
                // 调用相机拍照
                case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                    if (captureManager.getCurrentPhotoPath() != null) {
                        captureManager.galleryAddPic();

                        ArrayList<String> paths = new ArrayList<>();
                        paths.add(captureManager.getCurrentPhotoPath());
                        loadAdpater(paths, requestCode);
                        Log.e("==========", paths.get(1));
                    }
                    break;
            }
        }
    }

    private void loadAdpater(ArrayList<String> paths, int code) {
        switch (code) {
            case REQUEST_CAMERA_CODE_ONE:
                loadOne(paths);
                break;
            case REQUEST_PREVIEW_CODE_ONE:
                loadOne(paths);
                break;
        }
    }

    private void loadOne(ArrayList<String> paths) {
        if (imagePathsOne == null) {
            imagePathsOne = new ArrayList<>();
        }
        imagePathsOne.clear();
        imagePathsOne.addAll(paths);

        if (paths.size() > 0) {
            ivEmptyOne.setVisibility(View.GONE);
        } else {
            ivEmptyOne.setVisibility(View.VISIBLE);
        }

        try {
            JSONArray obj = new JSONArray(imagePathsOne);
            Log.e("--", obj.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (gridAdapterOne == null) {
            gridAdapterOne = new GridAdapter(imagePathsOne);
            gridViewOne.setAdapter(gridAdapterOne);
            Log.e("----------------", "ddd==" + imagePathsOne.size());
        } else {
            gridAdapterOne.notifyDataSetChanged();
        }
    }

    private class GridAdapter extends BaseAdapter {
        private ArrayList<String> listUrls;

        public GridAdapter(ArrayList<String> listUrls) {
            this.listUrls = listUrls;
        }

        @Override
        public int getCount() {
            if (listUrls.size() == 9) {
                return 9;
            } else {
                return listUrls.size() + 1;
            }

        }

        @Override
        public String getItem(int position) {
            return listUrls.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                convertView = getLayoutInflater().inflate(R.layout.item_image, null);
                imageView = (ImageView) convertView.findViewById(R.id.imageView);
                convertView.setTag(imageView);
                // 重置ImageView宽高
//                LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(columnWidth, columnWidth);
//                imageView.setLayoutParams(params);
            } else {
                imageView = (ImageView) convertView.getTag();
            }

            if (position == listUrls.size()) {
                imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.icon_addpic_unfocused));
                if (position == 9) {
                    imageView.setVisibility(View.GONE);
                }
            } else {
                Glide.with(mContext)
                        .load(new File(getItem(position)))
                        .placeholder(R.mipmap.default_error)
                        .error(R.mipmap.default_error)
                        .centerCrop()
                        .crossFade()
                        .into(imageView);
            }
            return convertView;
        }
    }

}
